<?php
/**
 * Created by PHPStorm
 * User: xiest
 * Date: 2021/10/8
 * Email: <939369942@qq.com>
 */
namespace app\controller\api\user;

use app\BaseController;
use app\common\repositories\user\UserBalanceRepository;
use app\common\repositories\user\UserExtractRepository as repository;
use app\common\repositories\user\UserRepository;
use think\App;
use think\exception\ValidateException;
use think\facade\Db;

class Extract extends BaseController
{
    protected repository $repository;

    public function __construct(App $app, repository $repository)
    {
        parent::__construct($app);
        $this->repository = $repository;
    }


    public function lst()
    {
        [$page, $limit] = $this->page();
        $where = ['uid'=>request()->uid()];
        return app('json')->success($this->repository->getApiList($where,$page,$limit));
    }


    public function create()
    {

        $params = $this->request->params([
           'code','price','phone','style'
        ]);


        $this->validate($params,[
            'style|提现方式'=>'require',
            'phone|手机号'=>'require|mobile',
            'code|收款码'=>'require',
            'price|提现金额'=>'require'
        ]);

        if($params['price']<0){
            throw new ValidateException('提现金额不能小于0');
        }

 //       $price = input('price');
//        if($price < 10)
//            throw new ValidateException('最低提现10元');
//
//        if($price > 500)
//            throw new ValidateException('最高提现500元');

/*        $rate = systemConfig('extract_fee') ?: 0;

        $real_price = $price; //bcmul($price,bcsub(1,$rate,4),2);
        if($real_price <= 0)
            throw new ValidateException('提现失败');*/

        $user = app()->make(UserRepository::class)->get(request()->uid());
        if($user->balance < $params['price']){
            throw new ValidateException('余额不足');
        }

        try {
            Db::startTrans();

            /**@var $balanceMake UserBalanceRepository**/
            $balanceMake = app()->make(UserBalanceRepository::class);
            $balanceMake->recordBalance($user->uid,0,'extract','提现',$params['price']);

            $this->repository->create([
                'uid'=>$user->uid,
                'order_no'=>getOrderSn('TX'),
                'price'=>$params['price'],
                'real_price'=>$params['price'],
                'code'=>$params['code'],
                'phone'=>$params['phone'],
                'style'=>$params['style'],
                'status'=>0
            ]);
            // #todo 微信转账到零钱

            Db::commit();
            return success('提现成功');
        }catch (\Exception $exception){
            Db::rollback();
        }

        return success('提现失败');
    }

}